package com.android.meige.fragment.detail;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.meige.R;
import com.android.meige.activity.BaseObject;
import com.android.meige.fragment.BaseLazyFragment;
import com.android.meige.model.detail.BrandGoodsListData;
import com.android.meige.model.group.BrandDiscountMainData;
import com.android.meige.model.group.BrandDiscountMainDataCallback;
import com.android.meige.utils.ConstantsUrl;
import com.android.meige.utils.HttpUtils;
import com.android.meige.utils.ObjectUtils;
import com.android.meige.view.group.VRefreshLayout;
import com.android.meige.view.recycleview.CustomLoadMoreView;
import com.android.meige.view.recycleview.CustomRecycleView;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.mcxtzhang.nestlistview.NestFullListView;
import com.mcxtzhang.nestlistview.NestFullListViewAdapter;
import com.mcxtzhang.nestlistview.NestFullViewHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.android.meige.R.id.bdmain_iv;

/**
 * Created by Administrator on 2017/6/29.
 */

public class Fragment_BDMain_TabList extends BaseLazyFragment implements BaseQuickAdapter.RequestLoadMoreListener {


    @BindView(R.id.main_top_bg)
    Toolbar mainTopBg;
    @BindView(R.id.listView)
    CustomRecycleView mRecyclerView;
    @BindView(R.id.swipe_refresh_layout)
    VRefreshLayout mRefreshLayout;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    @BindView(R.id.progress_loading)
    FrameLayout progressLoading;

    private View rootView;
    private AdaptList adapter;
    private LayoutInflater inflater;
    private boolean networkConnected;
    private FragmentActivity mcontext;
    private static final String ARG_PARAM1 = "param1";
    private int position;
    private static final String ARG_PARAM2 = "param2";
    private String bid;
    private int page;
    private BrandGoodsListData branddata = new BrandGoodsListData();
    private ArrayList<BrandDiscountMainData.DataBean.ListBean> listdata = new ArrayList<>();
    private View inflate;
    private TextView refresh_textView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            position = getArguments().getInt(ARG_PARAM1);
            bid = getArguments().getString(ARG_PARAM2);
        }
    }

    public static Fragment_BDMain_TabList newInstance(int position, String bid) {
        Fragment_BDMain_TabList fragment = new Fragment_BDMain_TabList();
        Bundle args = new Bundle();
        args.putInt(ARG_PARAM1, position);
        args.putString(ARG_PARAM2, bid);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initPrepare() {
        ReFreshData();
    }

    private LinearLayoutManager mLayoutManager;
    private GridLayoutManager mGridLayoutManager;

    private void initRecycle() {
        adapter = new AdaptList(mcontext, listdata, "0");
        adapter.setLoadMoreView(new CustomLoadMoreView());
        adapter.setOnLoadMoreListener(this, mRecyclerView);
        mLayoutManager = new LinearLayoutManager(mcontext);
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.GetToTop((ImageView) rootView.findViewById(R.id.top), 0);

        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public boolean onItemChildClick(BaseQuickAdapter adapter1, View view, int position) {
                switch (view.getId()) {
                    case R.id.bdmain_iv:
                        Intent intent_bd = new Intent(mcontext, BaseObject.class);
                        intent_bd.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "地区列表");
                        intent_bd.putExtra("catname", listdata.get(position).getCatname());
                        intent_bd.putExtra("top", listdata.get(position).getId());
                        startActivity(intent_bd);
                        break;
                }
                return false;
            }
        });
    }

    @Override
    protected void onInvisible() {

    }

    @Override
    protected void initData() {
        networkConnected = ObjectUtils.isNetworkConnected(getActivity());
        if (networkConnected) {
            page = 1;
            GetListData(page);
        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
        }
    }

    @Override
    protected View initView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        this.inflater = inflater;
        networkConnected = ObjectUtils.isNetworkConnected(getActivity());
        rootView = inflater.inflate(R.layout.layout_recycle_bdmainrefresh, container, false);
        ButterKnife.bind(this, rootView);
        mcontext = getActivity();
        mainTopBg.setVisibility(View.GONE);
        initRecycle();
        //  initHeadSort(goodsData);
        return rootView;
    }

    private void ReFreshData() {
        if (mRefreshLayout != null) {
            mRefreshLayout.setBackgroundColor(Color.TRANSPARENT);
            mRefreshLayout.setAutoRefreshDuration(400);
            mRefreshLayout.setRatioOfHeaderHeightToReach(1.5f);
            mRefreshLayout.addOnRefreshListener(new VRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    networkConnected = ObjectUtils.isNetworkConnected(mcontext);
                    if (networkConnected) {
                        mRefreshLayout.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mRefreshLayout.refreshComplete();
                                page = 1;
                                GetListData(page);
                            }
                        }, 1000);
                    } else {
                        ObjectUtils.toast(mcontext, "网络连接出现异常");
                    }
                }
            });
        }
    }

    @OnClick(R.id.click_resetnetwork_refresh)
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.click_resetnetwork_refresh:
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 3);
                page = 1;
                GetListData(page);
                break;

        }
    }

    @Override
    public void onLoadMoreRequested() {
        page = page + 1;
        GetListData(page);
    }

    private void GetListData(final int page) {
        networkConnected = ObjectUtils.isNetworkConnected(getActivity());
        String address = ConstantsUrl.domain + ConstantsUrl.BRANDDISCOUNTMAIN;
        HashMap<String, String> map = new HashMap<>();
        map.put("bid", bid);
        map.put("page", page + "");
        if (networkConnected) {
            HttpUtils.get(address, map, new BrandDiscountMainDataCallback() {

                @Override
                public void onError(Call call, Exception e, int id) {
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                }

                @Override
                public void onResponse(BrandDiscountMainData response, int id) {
                    if (response == null) {
                        ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
                        return;
                    }
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
                    if (response.getCode() == 0) {
                        BrandDiscountMainData.DataBean data = response.getData();
                        if (data == null || !ObjectUtils.listHasData(data.getList())) {
                            if (page == 1) {
                                noData.setVisibility(View.VISIBLE);
                            } else {
                                adapter.loadMoreEnd();
                            }
                            return;
                        }
                        List<BrandDiscountMainData.DataBean.ListBean> list = data.getList();
                        if (page == 1) {
                            listdata.clear();
                            listdata.addAll(list);
                            adapter.setNewData(list);
                            mRecyclerView.setLayoutManager(mLayoutManager);
                            mRecyclerView.setAdapter(adapter);
                        } else {
                            listdata.addAll(list);
                            adapter.addData(list);
                            adapter.loadMoreComplete();
                        }
                    } else {
                        if (page == 1) {
                            noData.setVisibility(View.VISIBLE);
                        } else {
                            adapter.loadMoreFail();
                            ObjectUtils.toast(mcontext, response.getMsg());
                        }
                    }
                }
            });
        } else {
            if (page == 1) {
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
            }
            ObjectUtils.toast(getActivity(), "网络连接出现异常");
            adapter.loadMoreFail();
        }
    }

    public class AdaptList extends BaseMultiItemQuickAdapter<BrandDiscountMainData.DataBean.ListBean, BaseViewHolder> {

        public AdaptList(Context context, ArrayList<BrandDiscountMainData.DataBean.ListBean> data, String type) {
            super(data);
            addItemType(ConstantsUrl.BRANDDISCOUNTMAINITEMTYPE, R.layout.item_list_bdmainlist);
        }

        @Override
        protected void convert(BaseViewHolder holder, final BrandDiscountMainData.DataBean.ListBean mainlistdata) {
            switch (holder.getItemViewType()) {
                case ConstantsUrl.BRANDDISCOUNTMAINITEMTYPE:
                    ObjectUtils.photo2(mContext, mainlistdata.getThumb(), ((ImageView) holder.getView(bdmain_iv)));
                    /**
                     * 插入活动
                     */
                    int currentposition = holder.getAdapterPosition();
                    holder.getView(R.id.progress_hot).setVisibility(View.INVISIBLE);
                    TextView h_name = holder.getView(R.id.h_name);
                    TextView h_discount = holder.getView(R.id.h_discount);
                    h_discount.setText(mainlistdata.getSale());
                    h_name.setText(mainlistdata.getCatname());
                    //品牌view
                    ImageView bdmain_iv = (ImageView) holder.getView(R.id.bdmain_iv);
                    holder.addOnClickListener(R.id.bdmain_iv);
                    final List<BrandDiscountMainData.DataBean.ListBean.Goods_list> goods_list = mainlistdata.getGoods_list();
                    if (!ObjectUtils.listHasData(goods_list)) {
                        holder.setVisible(R.id.fl_listview, false);
                        return;
                    } else {
                        holder.setVisible(R.id.fl_listview, true);
                    }
                    //水平滚动列表
                    NestFullListView tabrow = (NestFullListView) holder.getView(R.id.grid);
                    //        //动态设置选项卡宽度，超过2个可以滑动查看
                    DisplayMetrics metrics = new DisplayMetrics();
                    mcontext.getWindowManager().getDefaultDisplay().getMetrics(metrics);
                    int width = (int) (metrics.widthPixels / 2.5);
                    final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, LinearLayout.LayoutParams.MATCH_PARENT);
                    goods_list.add(new BrandDiscountMainData.DataBean.ListBean.Goods_list("1"));
                    tabrow.setAdapter(new NestFullListViewAdapter<BrandDiscountMainData.DataBean.ListBean.Goods_list>(R.layout.list_main_hor_adapter, goods_list) {
                        @Override
                        public void onBind(int position, BrandDiscountMainData.DataBean.ListBean.Goods_list testBean, NestFullViewHolder holder) {
                            if("1".equals(testBean.type)){
                                (holder.getView(R.id.item_grid_detail_like_ll)).setVisibility(View.GONE);
                                (holder.getView(R.id.seemore)).setVisibility(View.VISIBLE);
                            }else {
                                (holder.getView(R.id.item_grid_detail_like_ll)).setVisibility(View.VISIBLE);
                                (holder.getView(R.id.seemore)).setVisibility(View.GONE);
                                (holder.getView(R.id.item_grid_detail_like_ll)).setLayoutParams(params);
                                ((TextView) holder.getView(R.id.item_grid_detail_like_number_before)).getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
                                String price1 = testBean.getTeam_price();
                                SpannableString msp = new SpannableString("￥" + price1);
                                msp.setSpan(new AbsoluteSizeSpan(10, true), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                ((TextView) holder.getView(R.id.item_grid_detail_like_number_after)).setText(msp);
                                holder.setText(R.id.item_grid_detail_like_number_before, "￥" + testBean.getTeam_price());
                                holder.setText(R.id.item_grid_detail_like_title, testBean.getName());
                                ObjectUtils.photo2(mcontext, testBean.getImg_cover(), ((ImageView) holder.getView(R.id.item_grid_detail_like_img)));
                            }
                        }
                    });
                    tabrow.setOnItemClickListener(new NestFullListView.OnItemClickListener() {
                        @Override
                        public void onItemClick(NestFullListView nestFullListView, View view, int pos) {
                            ObjectUtils.ToDetailActivity(mcontext, 1, goods_list.get(pos).getId(), "");
                            if("1".equals(goods_list.get(pos).type)) {
                                Intent intent_bd = new Intent(mcontext, BaseObject.class);
                                intent_bd.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE,"地区列表");
                                intent_bd.putExtra("catname",mainlistdata.getCatname());
                                intent_bd.putExtra("top",mainlistdata.getId());
                                startActivity(intent_bd);

                            }else {
                                ObjectUtils.ToDetailActivity(mcontext, 1, goods_list.get(pos).getId(), "");
                            }
                        }
                    });
                    break;
            }
        }
    }
}
